#pragma once

#include "cstdio"
#include <cstdlib>
#include <iostream>
#include <vector>
#include <map>
#include <thread>
#include <chrono>
#include <set>
#include "cstring"
using namespace std;

#include <errno.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <fcntl.h>
#include <sys/epoll.h>
#include <sys/select.h>
#include <sys/time.h>
#include <pthread.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/uio.h>
#include <fcntl.h>
//////////////////////////////
typedef unsigned int ip_t;
typedef unsigned short port_t;

//////////////////////////////
#define X_ARRAY_CNT(v)	(sizeof(v)/sizeof((v)[0]))

static bool _xxx_printf = true;
#define X_P_INFO  \
    if(_xxx_printf){\
        printf("err!file:%s,line:%u,func:%s,last err=%u %s\n",\
            __FILE__,__LINE__,__FUNCTION__,errno,strerror(errno));\
    }


#define X_CHECK(v,ret) \
    if(0 == (v)){\
        X_P_INFO;\
        return ret;\
    }

#define X_CHECK_0(v,ret) \
    if(0 != (v)){\
        X_P_INFO;\
        return ret;\
    }

#define X_CHECK_NO_RET(v) \
    if(0 == (v)){\
        X_P_INFO;\
        return ;\
    }

#define X_CHECK_RET_BOOL(v) X_CHECK(v,false)
//////////////////////////////
#define invalid_sock -1
//////////////////////////////
#define X_NS_IN_SEC (1000*1000*1000)
static void sleep_ns(uint64_t ns){
    std::this_thread::sleep_for(std::chrono::nanoseconds(ns));
}

static void sleep_ms(uint64_t ms){
    sleep_ns(ms*1000*1000);
}

static uint64_t get_ns()
{
    return std::chrono::high_resolution_clock::now().time_since_epoch().count();
}
//////////////////////////////

bool cpu_bind(pthread_t th,int32_t cpu_idx)
{
    cpu_set_t mask;
    CPU_ZERO(&mask);
    CPU_SET(cpu_idx,&mask);
    return 0 ==  pthread_setaffinity_np(th,sizeof(mask),&mask);
}
//////////////////////////////
// 从命令行参数找指定key
// ret：key的idx，不存在返回-1
static int32_t xx_get_argidx(int argc, char** argv, const char* key)
{
	for (int i = 1; i < argc; ++i) {
		if (0 == strcmp(argv[i], key)) {
			return i;
		}
	}
	return -1;
}

// 从命令行参数找指定key对应val
// ret：不存在返回nullptr
// eg：-key1 val1，传入-key1返回val1
static const char* xx_get_arg(int argc, char** argv, const char* key) {
	int32_t idx = xx_get_argidx(argc, argv, key);
	// 没找到 || 后面没了
	if (-1 == idx|| idx == argc - 1) {
		return nullptr;
	}
	return argv[idx + 1];
}

static int64_t xx_get_arg_i64(int argc, char** argv, const char* key){
    const char* val = xx_get_arg(argc, argv, key);
    return atoll(val);
}

#define xx_arg_have(key)  (-1 != xx_get_argidx(argc,argv,key))
#define xx_arg_str(key)   (xx_get_arg(argc,argv,key))
#define xx_arg_int(key)   (xx_get_arg_i64(argc,argv,key))



//////////////////////////////

